using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class MapView : MonoBehaviour
{
    [Header("节点配置")]
    [SerializeField] private MapItem mapItemPrefab;
    [SerializeField] private Transform root;

    [Header("连线配置")]
    [SerializeField] private LineView linePrefab;

    [Header("英雄")]
    [SerializeField] private GameObject heroMapItem;

    [Header("毒圈配置")]
    [SerializeField] private MeshFilter poisonMeshFilter;
    [SerializeField] private MeshRenderer poisonMeshRenderer;

    private List<MapItem> mapItems = new List<MapItem>();
    private List<LineView> lines = new List<LineView>();
    private Dictionary<int, MapItem> idToItem = new Dictionary<int, MapItem>();

    private Dictionary<int, List<int>> connections;
    private Dictionary<int, MapItemType> typeDict;
    private Dictionary<int, Vector3> posDict;

    private List<int> poisonVertexIds = new List<int>();
    private int nowId;

    /// <summary>
    /// 初始化
    /// </summary>
    public void Setup()
    {
        connections = MapSystem.Instance.connections;
        typeDict = MapSystem.Instance.typeDict;
        posDict = MapSystem.Instance.posDict;
        poisonVertexIds = MapSystem.Instance.poisonVertexIds;
        nowId = MapSystem.Instance.nowId;

        ClearMap();
        CreateMapItems();
        BuildConnections();
        BuildLines();

        RefreshView();
    }

    private void ClearMap()
    {
        foreach (var item in mapItems) Destroy(item.gameObject);
        foreach (var line in lines) Destroy(line.gameObject);
        mapItems.Clear();
        lines.Clear();
        idToItem.Clear();
    }

    private void CreateMapItems()
    {
        foreach (var kv in posDict)
        {
            int id = kv.Key;
            MapItem item = Instantiate(mapItemPrefab, root);
            item.name = $"MapItem_{id}";
            item.transform.localPosition = kv.Value;

            MapItemType type = typeDict.ContainsKey(id) ? typeDict[id] : MapItemType.Fight;
            item.Setup(id, type, new List<MapItem>());

            mapItems.Add(item);
            idToItem[id] = item;
        }
    }

    private void BuildConnections()
    {
        foreach (var kvp in connections)
        {
            int id = kvp.Key;
            if (!idToItem.ContainsKey(id)) continue;

            MapItem current = idToItem[id];
            foreach (int nextId in kvp.Value)
            {
                if (!idToItem.ContainsKey(nextId)) continue;
                current.nextMapItem.Add(idToItem[nextId]);
            }
        }
    }

    private void BuildLines()
    {
        foreach (var kvp in connections)
        {
            int id = kvp.Key;
            if (!idToItem.ContainsKey(id)) continue;

            MapItem current = idToItem[id];
            foreach (int nextId in kvp.Value)
            {
                if (!idToItem.ContainsKey(nextId) || id >= nextId) continue;

                MapItem nextItem = idToItem[nextId];
                LineView line = Instantiate(linePrefab, root);
                line.Setup(current, nextItem);
                lines.Add(line);
            }
        }
    }

    public void RefreshView()
    {
        nowId = InfoSystem.Instance.nowMapItemId;
        poisonVertexIds = MapSystem.Instance.poisonVertexIds;

        UpdateClickableNodes();
        DrawPoisonPolygon();
    }

    public void UpdateClickableNodes()
    {
        foreach (var item in mapItems)
            item.canMouseDown = false;

        if (!idToItem.ContainsKey(nowId))
        {
            Debug.LogWarning($"[MapView] nowId={nowId} 不存在，默认设置起点=0");
            nowId = 0;
            InfoSystem.Instance.nowMapItemId = 0;
        }

        MapItem current = idToItem[nowId];
        foreach (var next in current.nextMapItem)
            next.canMouseDown = true;

        SetMapItemHero();
    }

    private void SetMapItemHero()
    {
        if (!idToItem.ContainsKey(nowId))
        {
            heroMapItem.SetActive(false);
            return;
        }

        heroMapItem.SetActive(true);
        if (heroMapItem.transform.parent != idToItem[nowId].transform)
        {
            heroMapItem.transform.SetParent(idToItem[nowId].transform, false);
            heroMapItem.transform.localPosition = Vector3.zero;
        }
    }

public void DrawPoisonPolygon()
{
    if (poisonVertexIds == null || poisonVertexIds.Count < 3)
    {
        Debug.LogWarning("[Poison] 顶点数量不足，无法生成毒圈 Mesh");
        poisonMeshRenderer.enabled = false;
        return;
    }

    Vector3 center = posDict[0]; // 中心点
    List<Vector3> vertices = new List<Vector3> { center };

    foreach (int id in poisonVertexIds)
    {
        if (posDict.TryGetValue(id, out var pos))
            vertices.Add(pos);
        else
            Debug.LogWarning($"[Poison] posDict 不存在 id={id}");
    }

    int N = vertices.Count - 1; // 外围顶点数
    List<int> triangles = new List<int>();

    // 正面三角形
    for (int i = 1; i <= N; i++)
    {
        int next = (i % N) + 1;
        triangles.Add(0);   // 中心
        triangles.Add(i);   // 当前
        triangles.Add(next);// 下一个
    }

    // 反面三角形（顺序反转）
    for (int i = 1; i <= N; i++)
    {
        int next = (i % N) + 1;
        triangles.Add(0);
        triangles.Add(next);
        triangles.Add(i);
    }

    Mesh mesh = poisonMeshFilter.mesh;
    if (mesh == null) mesh = new Mesh();
    mesh.Clear();

    mesh.vertices = vertices.ToArray();
    mesh.triangles = triangles.ToArray();
    mesh.RecalculateNormals();
    mesh.RecalculateBounds();

    poisonMeshFilter.mesh = mesh;

    if (poisonMeshRenderer != null)
    {
        Material mat = poisonMeshRenderer.material;
        mat.color = new Color(1f, 0f, 0f, 0.3f);
        mat.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
        mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
        mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
        mat.SetInt("_ZWrite", 0);
        mat.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
    }
    poisonMeshRenderer.enabled = true; // 满足条件时显示
    Debug.Log($"[Poison] Mesh 更新完成，顶点={vertices.Count}, 三角形={triangles.Count / 3}");
}









}
